package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * es文章分页检索
     *
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) throws IOException {
        //1.检查参数
        if(userSearchDto == null || StringUtils.isBlank(userSearchDto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //异步调用
        //获取用户id
        ApUser apUser = ApThreadLocalUtil.getUser();
        if (apUser != null) {
            //异步调用保存历史记录
            Integer userId = apUser.getId();
            apUserSearchService.insert(userSearchDto.getSearchWords(), userId);
        }
        //2.创建搜索请求对象，并且指定索引库
        SearchRequest searhRequest = new SearchRequest("app_info_article");
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //关键字查询
        if (userSearchDto.getSearchWords() != null) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", userSearchDto.getSearchWords()));
        }
        //小于最小时间
        if (userSearchDto.getMinBehotTime() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(userSearchDto.getMinBehotTime()));
        }

        searhRequest.source().query(boolQueryBuilder);

        //分页
        searhRequest.source().from(0).size(userSearchDto.getPageSize());

        //排序
        searhRequest.source().sort("publishTime", SortOrder.DESC);

        //高亮
        HighlightBuilder highlight = new HighlightBuilder();
        highlight.field("title");
        highlight.requireFieldMatch(false);
        highlight.preTags("<font style='color: red; font-size: inherit;'>");
        highlight.postTags("</font>");
        searhRequest.source().highlighter(highlight);

        //1.调用es的搜索api
        SearchResponse response = client.search(searhRequest, RequestOptions.DEFAULT);
        //3. 结果封装
        return result(response);
    }

    /**
     * 抽取的封装结果的方法
     *
     * @param response
     * @return
     */
    private ResponseResult result(SearchResponse response) {

        List<Map> list = new ArrayList<>();

        //获取命中的结果
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            //获取查询结果，返回是map集合
            Map<String, Object> map = hit.getSourceAsMap();
            //高亮数据封装
            //如果高亮域中有值
            if (hit.getHighlightFields().size() > 0) {
                //取出高亮域
                Text[] titles = hit.getHighlightFields().get("title").fragments();
                if (titles.length > 0) {
                    //把高亮之后的h_tile=<font>测试</font>
                    map.put("h_title", titles[0].toString());
                }
            } else {
                //表示没有高亮域，我们则把h_title=测试
                map.put("h_title", map.get("title"));
            }
            //把获取的结果封装到list
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }
}
